package com.txx.app.management.common.ui;

import android.app.Dialog;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.qihoo360.replugin.RePlugin;
import com.rsq.function.txxpluginsdk.user.TXXUserDBHelper;
import com.rsq.function.txxpluginsdk.user.TXXUserSPManager;
import com.rsq.function.txxpluginsdk.user.bean.TXXUser;
import com.tendcloud.tenddata.TCAgent;
import com.txx.app.management.ManagementApp;
import com.txx.app.management.R;
import com.txx.app.management.common.bean.LogOut;
import com.txx.app.management.common.utils.MyDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by renshiqian on 2018/10/30.
 */
public class BaseActivity extends FragmentActivity {
    //protected MyDownloadService.MyBinder myBinder;
    private Dialog dialog;
    private ManagementApp app;
    private MyDialog myDialog;
    //apk升级使用Service绑定的连接
    /*protected ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder = (MyDownloadService.MyBinder) service;
            myBinder.startDownload();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };*/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /*app = ManagementApp.getApp();
        app.addToStack(this);*/
        ActivityStack.getInstance().addActivity(this);
        EventBus.getDefault().register(this);
//        String activityName = getClass().getSimpleName();
//        if (activityName.equals("LoginActivity") || activityName.equals("ValidateActivity")) {
        createView();
        if(RePlugin.getHostContext() != null) {
            initUserInfo();
        }
        myDialog = new MyDialog(this);
//        HttpCancelUtil.init();
//        } else {
//            createView2();
//        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void popupNetWorkWindow(LogOut state) {
        if (state.isLogout()) {
            myDialog.showDialog(R.layout.dialog_verify);
            TextView tv_msg1 = (TextView) myDialog.findViewById(R.id.tv_warn_msg);
            tv_msg1.setText(state.getDesc());
            myDialog.findViewById(R.id.tv_warn_true).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //app.logout();
                    myDialog.dismiss();
                }
            });

        }
    }

    /**
     * 初始化宿主的用户信息
     */
    private void initUserInfo() {
        ManagementApp.TOKEN = null == TXXUserSPManager.getInstance(ManagementApp.getHostContext()).getToken()
                ? "" : TXXUserSPManager.getInstance(ManagementApp.getHostContext()).getToken();
        ManagementApp.USER_STAFF_BUILDER = null == TXXUserSPManager.getInstance(ManagementApp.getHostContext()).getStaffBuidler()
                ? "" : TXXUserSPManager.getInstance(ManagementApp.getHostContext()).getStaffBuidler();
        if (!TextUtils.isEmpty(ManagementApp.USER_STAFF_BUILDER)) {
            TXXUser userInfo = TXXUserDBHelper.getInstance(ManagementApp.getHostContext()).getUserFromCache(ManagementApp.USER_STAFF_BUILDER);
            if (userInfo != null) {
                ManagementApp.USER_ROLES = userInfo.getRoles();
                ManagementApp.USER_STAFF_NUMBER = userInfo.getStaffNumber();
                ManagementApp.USER_CHANNEL = userInfo.getChannel();
                ManagementApp.USER_ADDRESS = userInfo.getAddress();
                ManagementApp.USER_ORG_CODE = userInfo.getOrgCode();
                ManagementApp.USER_ORG_DESC = userInfo.getOrgDesc();
                ManagementApp.USER_NAME = userInfo.getName();
                ManagementApp.USER_NICK_NAME = userInfo.getNickName();
                ManagementApp.USER_AGT_TYPE = userInfo.getAgtype();
                ManagementApp.USER_CARD_SEQ = userInfo.getCardSeq();
                ManagementApp.USER_CARD_TYPE = userInfo.getCardType();
                ManagementApp.USER_EMPLOYEE_NUMBER = userInfo.getEmployeeNumber();
                ManagementApp.USER_ENTER_DATE = userInfo.getEnterDate();
                ManagementApp.USER_GENDER = userInfo.getGender();
                ManagementApp.USER_HEAD_URL = userInfo.getHeadUrl();
                ManagementApp.USER_HIGHEST_EDU = userInfo.getHighestEdu();
                ManagementApp.USER_HONOR_DESC = userInfo.getHonorDesc();
                ManagementApp.USER_MOBILE = userInfo.getMobile();
                ManagementApp.USER_PASSWORD = userInfo.getPassword();
                ManagementApp.USER_RANK_DESC = userInfo.getRankDesc();
                ManagementApp.USER_WORK_LIFE = userInfo.getWorkLife();
                ManagementApp.USER_UCM_COMPANY_CODE = userInfo.getUcmCompanyCode();
                ManagementApp.USER_UCM_EMPLOYNO = userInfo.getUcmEmployNo();
                ManagementApp.USER_TOTAL_CUSTOMER_NUM = userInfo.getTotalCustomerNum();
                ManagementApp.USER_TOTAL_POLICY_NUM = userInfo.getTotalPolicyNum();
                ManagementApp.USER_BRANCH_TYPE = userInfo.getBranchType();
                ManagementApp.USER_RECEIPTNO = userInfo.getReceiptno();
            }
        }
    }

    /*@Subscribe(threadMode = ThreadMode.MAIN)
    public void showNetWorkChangeDialog(NetWorkStateChange netWorkStateChange) {
        if (netWorkStateChange.getConnectType() == ConnectivityManager.TYPE_MOBILE) {
            SPUtils spUtils = new SPUtils("autoLogin");
            boolean isGLoad = spUtils.getBoolean("isGLoad");
            if (isGLoad) {
                MyToast.showLong("您已允许4G环境下载视频");
            } else {
                DbDwonUtil dbUtil = DbDwonUtil.getInstance();
                List<DownInfo> allData = dbUtil.queryDownAll();
                for (DownInfo info : allData) {
                    if (info.getState() != DownState.FINISH) {
                        info.setState(DownState.PAUSE);
                    }
                }
                HttpDownManager manager = HttpDownManager.getInstance();
                manager.pauseAll();
                Constant.isVideoLoad = false;
                MyToast.showLong("4G环境视频已暂停下载");
            }
        }
    }*/

    /**
     * 不依赖系统字体大小变化
     *
     * @return
     */
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    /**
     * 无网络连接时弹出
     */
   /* NetErrorPopupWindow netErrorPopupWindow;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void popupNetWorkWindow(NetWorkChange state) {
        if (netErrorPopupWindow != null && netErrorPopupWindow.isShowing()) {
            netErrorPopupWindow.dismiss();
            netErrorPopupWindow = null;
        }
        if (!state.isConnected()) {
            netErrorPopupWindow = new NetErrorPopupWindow(this);
            netErrorPopupWindow.showAtDropDownRight(tvLoginTitle);
        }
    }*/
    public void dismissProgressDialog() {
        if (dialog != null && !isFinishing()) {
            dialog.dismiss();
        }
    }

    private void createView() {
        View layout = View.inflate(this, R.layout.dialog_loading_bg, null);
        dialog = new Dialog(this, R.style.dialog);
        dialog.setCancelable(true);
        dialog.setContentView(layout);
    }

    private void createView2() {
        View layout = View.inflate(this, R.layout.dialog_loading_bg2, null);
        dialog = new Dialog(this, R.style.dialog);
        dialog.setCancelable(true);
        dialog.setContentView(layout);
    }

    public void showProgressDialog() {
        if (dialog != null && !isFinishing()) {
            dialog.show();
        }
    }

    public void showProgressDialog(boolean cancelable) {
        if (dialog != null && !isFinishing()) {
            dialog.setCancelable(false);
            dialog.show();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        TCAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        TCAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dismissProgressDialog();
        EventBus.getDefault().unregister(this);
//        HttpCancelUtil.cancelAll();
    }

    @Override
    public void finish() {
        super.finish();
        ActivityStack.getInstance().finishActivity(this);
    }
    //------------------------------------高德定位开始--------------------------------------------------------------

    /*protected AMapLocationClientOption locationOption = null;
    protected AMapLocationClient locationClient;
    *//**
     * 连续定位监听
     *//*
    protected AMapLocationListener locationContinueListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {
                StringBuffer sb = new StringBuffer();
                //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
//
//                    sb.append("定位类型: " + location.getLocationType() + "\n");
//                    sb.append("经    度    : " + location.getLongitude() + "\n");
//                    sb.append("纬    度    : " + location.getLatitude() + "\n");
//                    sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
//                    sb.append("提供者    : " + location.getProvider() + "\n");
//                    sb.append("速    度    : " + location.getSpeed() + "米/秒" + "\n");
//                    sb.append("角    度    : " + location.getBearing() + "\n");
//                    // 获取当前提供定位服务的卫星个数
//                    sb.append("星    数    : " + location.getSatellites() + "\n");
//                    sb.append("国    家    : " + location.getCountry() + "\n");
//                    sb.append("省            : " + location.getProvince() + "\n");
//                    sb.append("市            : " + location.getCity() + "\n");
//                    sb.append("城市编码 : " + location.getCityCode() + "\n");
//                    sb.append("区            : " + location.getDistrict() + "\n");
//                    sb.append("区域 码   : " + location.getAdCode() + "\n");
//                    sb.append("地    址    : " + location.getAddress() + "\n");
//                    sb.append("兴趣点    : " + location.getPoiName() + "\n");
//                    //定位完成的时间
//                    sb.append("定位时间: " + GaodeUtils.formatUTC(location.getTime(), "yyyy-MM-dd HH:mm:ss") + "\n");
//
//                    sb.append("错误码:" + location.getErrorCode() + "\n");
//                    sb.append("错误信息:" + location.getErrorInfo() + "\n");
//                    sb.append("错误描述:" + location.getLocationDetail() + "\n");
//                sb.append("***定位质量报告***").append("\n");
//                sb.append("* WIFI开关：").append(location.getLocationQualityReport().isWifiAble() ? "开启" : "关闭").append("\n");
//                sb.append("* GPS状态：").append(GaodeUtils.getGPSStatusString(location.getLocationQualityReport().getGPSStatus())).append("\n");
//                sb.append("* GPS星数：").append(location.getLocationQualityReport().getGPSSatellites()).append("\n");
//                sb.append("****************").append("\n");
//                //定位之后的回调时间
//                sb.append("回调时间: " + GaodeUtils.formatUTC(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss") + "\n");
//
//                //解析定位结果
//                String result = sb.toString();
//                MyLog.wtf("YG_TAG", "定位结果===>" + result);
                //将经纬度，地址放入SP
                 String longtitude = "" + location.getLongitude();
                String latitude = "" + location.getLatitude();
                String errorInfo = location.getErrorInfo();
                String address = "" + location.getAddress();
                String resultCode = ""+location.getErrorCode();
                   if (location.getErrorCode() == 0) {
                    sb.append("定位成功" + "\n");
                } else {
                    sb.append("定位失败" + "\n");
                }
                GaodeUtils.putLocationIntoSp(longtitude, latitude, address , resultCode);
            } else {
                MyLog.wtf("YG_TAG", "定位失败！！！");
            }
        }
    };

    *//**
     * 单次定位监听
     *//*
    protected AMapLocationListener locationOnceListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {
                StringBuffer sb = new StringBuffer();
                //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
//
//                    sb.append("定位类型: " + location.getLocationType() + "\n");
//                    sb.append("经    度    : " + location.getLongitude() + "\n");
//                    sb.append("纬    度    : " + location.getLatitude() + "\n");
//                    sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
//                    sb.append("提供者    : " + location.getProvider() + "\n");
//                    sb.append("速    度    : " + location.getSpeed() + "米/秒" + "\n");
//                    sb.append("角    度    : " + location.getBearing() + "\n");
//                    // 获取当前提供定位服务的卫星个数
//                    sb.append("星    数    : " + location.getSatellites() + "\n");
//                    sb.append("国    家    : " + location.getCountry() + "\n");
//                    sb.append("省            : " + location.getProvince() + "\n");
//                    sb.append("市            : " + location.getCity() + "\n");
//                    sb.append("城市编码 : " + location.getCityCode() + "\n");
//                    sb.append("区            : " + location.getDistrict() + "\n");
//                    sb.append("区域 码   : " + location.getAdCode() + "\n");
//                    sb.append("地    址    : " + location.getAddress() + "\n");
//                    sb.append("兴趣点    : " + location.getPoiName() + "\n");
//                    //定位完成的时间
//                    sb.append("定位时间: " + GaodeUtils.formatUTC(location.getTime(), "yyyy-MM-dd HH:mm:ss") + "\n");
//
//
//                    sb.append("错误码:" + location.getErrorCode() + "\n");
//                    sb.append("错误信息:" + location.getErrorInfo() + "\n");
//                    sb.append("错误描述:" + location.getLocationDetail() + "\n");
//
//                sb.append("***定位质量报告***").append("\n");
//                sb.append("* WIFI开关：").append(location.getLocationQualityReport().isWifiAble() ? "开启" : "关闭").append("\n");
//                sb.append("* GPS状态：").append(GaodeUtils.getGPSStatusString(location.getLocationQualityReport().getGPSStatus())).append("\n");
//                sb.append("* GPS星数：").append(location.getLocationQualityReport().getGPSSatellites()).append("\n");
//                sb.append("****************").append("\n");
//                //定位之后的回调时间
//                sb.append("回调时间: " + GaodeUtils.formatUTC(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss") + "\n");
//                //解析定位结果，
//                String result = sb.toString();
//                MyLog.wtf("YG_TAG", "定位结果===>" + result);
                //将经纬度，地址放入SP
                 String longtitude = "" + location.getLongitude();
                String latitude = "" + location.getLatitude();
                String errorInfo = location.getErrorInfo();
                String address = "" + location.getAddress();
                String resultCode = "" + location.getErrorCode();
                GaodeUtils.putLocationIntoSp(longtitude, latitude, address,resultCode);
            } else {
                MyLog.wtf("YG_TAG", "定位失败！！！");
            }
        }
    };

    *//***
     * 是否进行连续定位
     * @param isContinueLocate
     *//*
    protected void initLocation(Activity context, boolean isContinueLocate) {
        //初始化client
        locationClient = GaodeUtils.getLocationClient(this.getApplicationContext());
        locationOption = GaodeUtils.getDefaultOption();
        //设置定位参数
        locationClient.setLocationOption(locationOption);
        // 设置定位监听
        if (isContinueLocate) {
            locationClient.setLocationListener(locationContinueListener);
        } else {
            locationClient.setLocationListener(locationOnceListener);
        }

        GaodeUtils.startLocation();

    }*/

    //------------------------------------高德定位结束--------------------------------------------------------------

}
